package components

import (
	"fmt"

	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func InitGorm() *gorm.DB {
	username := viper.GetString("mysql.username")
	password := viper.GetString("mysql.password")
	port := viper.GetString("mysql.port")
	host := viper.GetString("mysql.host")
	database := viper.GetString("mysql.database")

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port, database)
	// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("------err----", err)
		return nil
	}
	return db
}
